package io.github.weiranyi.dao.impl;

import io.github.weiranyi.dao.AccountDao;
import io.github.weiranyi.entity.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AccountDaoImpl implements AccountDao {
    /* 1.创建DBUtils工具类，传入连接池
     * QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
     */
    private QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    // 查询数据库的所有信息，返回一个list集合，集合类型是Account
    @Override
    public List<Account> findAll() {
        // 声明SQL
        String sql = "select * from account where id = ?";
        // 执行SQL
        List<Account> list = null;
        try {
            // 查询的时候用query(sql,BeanListHandler<Account>)
            list = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;

    }

    @Override
    public Account findById(Integer id) {
        // 编写sql
        String sql = "select * from account where id = ?";
        Account account = null;
        try {
            // 查询返回值是单个 new BeanHandler<Account>(Account.class)
            account = queryRunner.query(sql, new BeanHandler<Account>(Account.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return account;
    }

    @Override
    public void save(Account account) {
        // 编写sql
        String sql = "insert into account values(null,?,?)";
        // 执行SQL
        try {
            // 增删改 queryRunner.update(sql, account.getName(), account.getMoney());
            queryRunner.update(sql, account.getName(), account.getMoney());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public void update(Account account) {
        // 编写sql
        String sql = "update account set name = ?,money = ? where id = ?";
        // 执行SQL
        try {
            queryRunner.update(sql, account.getName(), account.getMoney(), account.getId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public void delete(Integer id) {
        // 编写sql
        String sql = "delete from account where id = ?";
        // 执行sql
        try {
            queryRunner.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
